package leetcode101.sort;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

/**
 * @author Synhard
 * @version 1.0
 * @Class Code3
 * @Description 451. Sort Characters By Frequency
 * Given a string, leetcode101.sort it in decreasing order based on the frequency of characters.
 *
 * Example 1:
 *
 * Input:
 * "leetcode101.tree"
 *
 * Output:
 * "eert"
 *
 * Explanation:
 * 'e' appears twice while 'r' and 't' both appear once.
 * So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
 * Example 2:
 *
 * Input:
 * "cccaaa"
 *
 * Output:
 * "cccaaa"
 *
 * Explanation:
 * Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
 * Note that "cacaca" is incorrect, as the same characters must be together.
 * Example 3:
 *
 * Input:
 * "Aabb"
 *
 * Output:
 * "bbAa"
 *
 * Explanation:
 * "bbaA" is also a valid answer, but "Aabb" is incorrect.
 * Note that 'A' and 'a' are treated as two different characters.
 * @tel 13001321080
 * @email 823436512@qq.com
 * @date 2021-03-30 9:40
 */
public class Code3 {

    public static void main(String[] args) {
        frequencySort("cccaaa");
    }

    public static String frequencySort(String s) {
        HashMap<Character, Integer> bucket = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            if (bucket.get(s.charAt(i)) == null) {
                bucket.put(s.charAt(i), 1);
            } else {
                bucket.put(s.charAt(i), bucket.get(s.charAt(i)) + 1);
            }
        }
        List<Entry<Character, Integer>> list = new ArrayList<>(bucket.entrySet());
        Collections.sort(list, (o1, o2) -> o2.getValue() - o1.getValue());
        String res = "";
        for (int i = 0; i < list.size(); i++) {
            char c = list.get(i).getKey();
            int t = list.get(i).getValue();
            while (t > 0) {
                res += c;
                t--;
            }
        }
        return res;
    }


}

